from stock.stock_base_daily import daily_directory,get_daily_by_file,read_files
import os
import pandas as pd
from logger import logger
from stock.moving_avg import calculate_moving_avg

# 定义列名 date,code,open,high,low,close,preclose,volume,amount,adjustflag,turn,tradestatus,pctChg,isST
column_names = ['date', 'code', 'open', 'high', 'low', 'close', 'isST'
    , 'MA5', 'MA5_slope', 'MA5_max', 'MA5_min', 'MA10', 'MA10_slope', 'MA10_max', 'MA10_min', 'MA20', 'MA20_slope',
                'MA20_max', 'MA20_min'
    , 'MA30', 'MA30_slope', 'MA30_max', 'MA30_min', 'MA60', 'MA60_slope', 'MA60_max', 'MA60_min', 'MA120',
                'MA120_slope', 'MA120_max', 'MA120_min', 'MA_ratio', 'MA_ratio_20', 'MA_ratio_40']


def check_daily_all():
    # 创建一个空的DataFrame
    rs = pd.DataFrame()
    # 获取目录中的所有文件
    dfs = read_files(daily_directory)
    print("load file complete!")
    for df in dfs:
        if len(df) > 200:
            try:
                df = calculate_moving_avg(df)
                df['MA_diff'] = df[['MA5', 'MA10', 'MA20', 'MA30','MA60','MA120']].max(axis=1) - df[['MA5', 'MA10', 'MA20', 'MA30','MA60','MA120']].min(axis=1)
                df['MA_ratio'] = df['MA_diff'] / df['MA120'] *100
                df['MA_ratio_5'] = df['MA_ratio'].shift(5)
                df['MA_ratio_20'] = df['MA_ratio'].shift(20)
                df['MA_ratio_40'] = df['MA_ratio'].shift(40)
                # 获取df中与rs具有相同列名的最后一行数据
                _value = check_consecutive_descending_dark_candles(df,3)
                last_row_index = df.index[-1]  # 获取最后一行的索引
                df.loc[last_row_index, 'model_1'] = _value
                _df = df.iloc[-1:]
                # new_df = last_row.to_frame()
                # 纵向合并
                print(_df['code'])
                rs = pd.concat([rs,_df], ignore_index=True)
                # rs = pd.concat([rs, new_df], ignore_index=True)
            except Exception as e:
                print(f"An error occurred: {e}")

    return rs


def check_consecutive_descending_dark_candles(df, n):
    df['pre_low'] = df['low'].shift(1)  # 由于已经 dropna，这里不会有 NaN
    # 取最后n个交易日的数据
    last_n_days = df.tail(n)
    # 确保 'open' 和 'close' 列没有 NaN 值
    # last_n_days = last_n_days.dropna(subset=['open', 'close'])
    # 检查每个交易日是否为阴线（收盘价低于开盘价）
    dark_candles = last_n_days['close'] < last_n_days['open']
    # 检查每日最低价是否依次下降
    # 使用 `.shift(1)` 来获取前一天的最低价，并与当前天的最低价进行比较
    descending_lows = last_n_days['low'] < last_n_days['pre_low']
    # 删除由于 shift 操作而产生的最后一个 NaN 值
    descending_lows = descending_lows.dropna()
    # 合并两个条件，注意两个条件的 Series 必须长度相同
    both_conditions_met = dark_candles & descending_lows
    # 检查是否所有的值都为True
    return both_conditions_met.all()


if __name__=="__main__":
    rs = check_daily_all()
    # rs['code'] = rs['code'].str.slice(start=-6, stop=None)
    rs.to_csv("ts.csv")